<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/main.css">
</head>

<body>

    <div id="calendar" class="calendar">
        <div>一</div>
        <div>二</div>
        <div>三</div>
        <div>四</div>
        <div>五</div>
        <div>六</div>
        <div>日</div>
    </div>

    <script>
        function createCalendar(el, year, month) {
            // 获取每月的天数
            const days = new Date(year, month, 0).getDate();


            // 获取本月最后一天是星期几
            const weekLast = new Date(year, month, 0).getDay();

            // 获取1号是星期几
            const week = new Date(year, month - 1, 1).getDay() || 7;

            //获取上个月的最后一天
            const datePre = new Date(year, month - 1, 0).getDate();

            // 保存所有单元格
            const divs = [];

            // 填充1号前的单元格
            for (let i = datePre - week + 2; i <= datePre; i++) {
                const div = document.createElement('div');
                div.innerHTML = i;
                divs.push(div);
            }

            // 将天数转换成对应的单元格（div）

            for (let i = 1; i <= days; i++) {
                const div = document.createElement('div');
                div.innerHTML = i;
                divs.push(div);
            }

            // 填充最后一天之后的单元格
            for (let i = 1; i <= 7 - weekLast; i++) {
                const div = document.createElement('div');
                div.innerHTML = i;
                divs.push(div);
            }
            el.append(...divs);
        }
        createCalendar(document.getElementById('calendar'), 2023, 6);
    </script>
</body>

</html>